package cn.sunxiansheng.seckill.token.controller;

import cn.sunxiansheng.redis.utils.RString;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Description: 基于Token校验避免订单重复提交
 *
 * @Author sun
 * @Create 2025/1/8 15:55
 * @Version 1.0
 */
@RestController
public class TokenController {

    @Resource
    private RString rString;

    /**
     * Token前缀
     */
    public static final String TOKEN_PREFIX = "token:order";

    /**
     * Token发放：用户进入详情页，后端生成一个Token，存到Redis中，并返回给前端
     *
     * @return
     */
    @RequestMapping("/getOrderToken")
    public String getOrderToken() {
        // 1.生成Token
        String token = UUID.randomUUID().toString();
        // 2.构建Key
        String key = rString.buildKeyByDefaultSeparator(TOKEN_PREFIX, token);
        // 3.存到Redis
        rString.setWithExpire(key, "token", 30, TimeUnit.MINUTES);
        // 4.将key返回给前端
        return key;
    }
}